<template>
  <div class="orders-container">
    <!-- 订单详情 -->
    <div v-if="orderNo" class="order-detail">
      <el-button @click="backToList" class="back-button">
        <el-icon><back /></el-icon> 返回列表
      </el-button>

      <!-- 加载中状态 -->
      <el-card v-if="loading" class="loading-card">
        <div class="loading-container">
          <el-skeleton :rows="10" animated />
        </div>
      </el-card>

      <!-- 订单详情内容 -->
      <el-card v-else-if="orderDetail" class="detail-card">
        <template #header>
          <div class="order-header">
            <span>订单号: {{ orderDetail.order.orderNo }}</span>
            <el-tag :type="getOrderStatusTag(orderDetail.order.status).type">
              {{ getOrderStatusTag(orderDetail.order.status).label }}
            </el-tag>
          </div>
        </template>

        <div class="order-info">
          <div class="order-section">
            <h3>收货信息</h3>
            <p>收货人: {{ orderDetail.order.receiverName }}</p>
            <p>联系电话: {{ orderDetail.order.receiverPhone }}</p>
            <p>收货地址: {{ orderDetail.order.receiverAddress }}</p>
          </div>

          <div class="order-section">
            <h3>订单信息</h3>
            <p>创建时间: {{ formatDate(orderDetail.order.createTime) }}</p>
            <p v-if="orderDetail.order.payTime">支付时间: {{ formatDate(orderDetail.order.payTime) }}</p>
            <p v-if="orderDetail.order.deliveryTime">发货时间: {{ formatDate(orderDetail.order.deliveryTime) }}</p>
            <p v-if="orderDetail.order.receiveTime">收货时间: {{ formatDate(orderDetail.order.receiveTime) }}</p>
          </div>
        </div>

        <div class="order-items">
          <h3>商品信息</h3>
          <el-table :data="orderDetail.orderItems" style="width: 100%">
            <el-table-column prop="productName" label="商品名称" />
            <el-table-column prop="productPrice" label="单价" width="100">
              <template #default="scope">
                ¥{{ scope.row.productPrice }}
              </template>
            </el-table-column>
            <el-table-column prop="quantity" label="数量" width="100" />
            <el-table-column prop="totalPrice" label="小计" width="120">
              <template #default="scope">
                ¥{{ scope.row.totalPrice }}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="order-summary">
          <div class="summary-item">
            <span>商品总价:</span>
            <span>¥{{ orderDetail.order.totalAmount }}</span>
          </div>
          <div class="summary-item" v-if="orderDetail.order.freightAmount">
            <span>运费:</span>
            <span>¥{{ orderDetail.order.freightAmount || 0 }}</span>
          </div>
          <div class="summary-item discount" v-if="orderDetail.order.promotionAmount > 0">
            <span>促销优惠:</span>
            <span class="discount-amount">-¥{{ orderDetail.order.promotionAmount.toFixed(2) }}</span>
            <el-tooltip content="促销优惠已应用" placement="top" v-if="hasDiscountPromotion && orderDetail.order.promotionAmount > 0">
              <el-tag size="small" type="danger" class="discount-tag">满减</el-tag>
            </el-tooltip>
          </div>
          <div class="summary-item total">
            <span>实付金额:</span>
            <span>¥{{ orderDetail.order.payAmount.toFixed(2) }}</span>
          </div>
        </div>

        <!-- 评价显示区域 -->
        <div v-if="orderDetail.order.status === 3 && orderReview" class="order-review-section">
          <h3>我的评价</h3>
          <div class="review-content">
            <div class="review-rating">
              <span class="rating-label">评分：</span>
              <el-rate
                v-model="orderReview.rating"
                disabled
                :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
                :texts="['很差', '较差', '一般', '不错', '很好']"
                show-text
              />
            </div>
            <div class="review-text">
              <span class="review-label">评价内容：</span>
              <p>{{ orderReview.content }}</p>
            </div>
            <div class="review-time">
              <span class="review-time-label">评价时间：</span>
              <span>{{ formatDate(orderReview.createTime) }}</span>
            </div>
          </div>
        </div>

        <div class="order-actions">
          <el-button v-if="orderDetail.order.status === 0" type="primary" @click="payOrder(orderDetail.order.orderNo)">去支付</el-button>
          <el-button v-if="orderDetail.order.status === 2" type="success" @click="confirmReceive(orderDetail.order.orderNo, orderDetail.order.status)">确认收货</el-button>
          <el-button v-if="orderDetail.order.status === 3 && !orderReview" type="warning" @click="reviewOrder(orderDetail.order)">评价订单</el-button>
          <el-button v-if="orderDetail.order.status === 0" type="danger" @click="cancelOrder(orderDetail.order.orderNo)">取消订单</el-button>
        </div>
      </el-card>

      <!-- 无数据状态 -->
      <el-card v-else class="empty-card">
        <el-empty description="订单详情加载失败或不存在" />
        <div class="empty-actions">
          <el-button type="primary" @click="handleReload">重新加载</el-button>
          <el-button @click="backToList">返回列表</el-button>
        </div>
      </el-card>
    </div>

    <!-- 订单列表 -->
    <div v-else class="order-list">
      <!-- 自定义订单状态分类导航条 -->
      <div class="order-status-nav">
        <div
          class="status-item"
          :class="{ active: activeTab === 'all' }"
          @click="activeTab = 'all'; handleStatusChange()"
        >
          全部订单
        </div>
        <div
          class="status-item"
          :class="{ active: activeTab === '0' }"
          @click="activeTab = '0'; handleStatusChange()"
        >
          待付款
        </div>
        <div
          class="status-item"
          :class="{ active: activeTab === '1' }"
          @click="activeTab = '1'; handleStatusChange()"
        >
          待发货
        </div>
        <div
          class="status-item"
          :class="{ active: activeTab === '2' }"
          @click="activeTab = '2'; handleStatusChange()"
        >
          待收货
        </div>
        <div
          class="status-item"
          :class="{ active: activeTab === '3' }"
          @click="activeTab = '3'; handleStatusChange()"
        >
          已完成
        </div>
      </div>

      <div v-if="orderList.length === 0" class="empty-orders">
        <el-empty description="暂无订单" />
      </div>

      <el-card v-for="order in orderList" :key="order.id" class="order-card">
        <div class="order-card-header">
          <div class="order-info">
            <span class="order-no">订单号: {{ order.orderNo }}</span>
            <span class="order-time">下单时间: {{ formatDate(order.createTime) }}</span>
          </div>
          <el-tag :type="getOrderStatusTag(order.status).type">
            {{ getOrderStatusTag(order.status).label }}
          </el-tag>
        </div>

        <div class="order-card-body" @click="viewOrderDetail(order.orderNo)">
          <!-- 这里应该显示订单项，但由于我们没有在订单列表API中返回订单项，所以这里只显示一些基本信息 -->
          <div class="order-summary-info">
            <p>收货人: {{ order.receiverName }}</p>
            <p>联系电话: {{ order.receiverPhone }}</p>
            <p>收货地址: {{ order.receiverAddress }}</p>
          </div>

          <div class="order-price-info">
            <div class="price-item">
              <span>商品总价:</span>
              <span>¥{{ order.totalAmount.toFixed(2) }}</span>
            </div>
            <div class="price-item discount" v-if="order.promotionAmount > 0">
              <span>促销优惠:</span>
              <span class="discount-amount">-¥{{ order.promotionAmount.toFixed(2) }}</span>
              <el-tooltip content="促销优惠已应用" placement="top" v-if="hasDiscountPromotion && order.promotionAmount > 0">
                <el-tag size="small" type="danger" class="discount-tag">满减</el-tag>
              </el-tooltip>
            </div>
            <div class="price-item">
              <span>实付金额:</span>
              <span class="pay-amount">¥{{ order.payAmount.toFixed(2) }}</span>
            </div>
          </div>
        </div>

        <div class="order-card-footer">
          <el-button v-if="order.status === 0" type="primary" size="small" @click.stop="payOrder(order.orderNo)">去支付</el-button>
          <el-button v-if="order.status === 2" type="success" size="small" @click.stop="confirmReceive(order.orderNo, order.status)">确认收货</el-button>
          <el-button v-if="order.status === 3 && !order.hasReview" type="warning" size="small" @click.stop="viewOrderDetail(order.orderNo)">去评价</el-button>
          <el-button v-if="order.status === 0" type="danger" size="small" @click.stop="cancelOrder(order.orderNo)">取消订单</el-button>
          <el-button type="primary" plain size="small" @click.stop="viewOrderDetail(order.orderNo)">查看详情</el-button>
        </div>
      </el-card>

      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>
  </div>

  <!-- 评价对话框 -->
  <el-dialog
    title="评价商品"
    v-model="reviewDialogVisible"
    width="500px"
  >
    <el-form :model="reviewForm" label-width="80px" :rules="reviewRules" ref="reviewFormRef">
      <el-form-item label="商品" prop="productName">
        <span>{{ reviewForm.productName }}</span>
      </el-form-item>
      <el-form-item label="评分" prop="rating">
        <el-rate
          v-model="reviewForm.rating"
          :colors="['#99A9BF', '#F7BA2A', '#FF9900']"
          :texts="['很差', '较差', '一般', '不错', '很好']"
          show-text
        />
      </el-form-item>
      <el-form-item label="评价内容" prop="content">
        <el-input
          v-model="reviewForm.content"
          type="textarea"
          :rows="4"
          placeholder="请输入您对商品的评价"
        />
      </el-form-item>
      <el-form-item label="匿名评价">
        <el-switch v-model="reviewForm.anonymous" />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="reviewDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitReview" :loading="reviewSubmitting">提交评价</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script lang="ts" setup>
import { ref, onMounted, computed, reactive, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { getOrders, getOrderDetail, cancelOrder as cancelOrderApi, payOrder as payOrderApi, getActivePromotions } from '@/api/user'
import { confirmReceiveOrder } from '@/api/order'
import { addReview, checkReview, getOrderReview } from '@/api/review'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Back } from '@element-plus/icons-vue'

const route = useRoute()
const router = useRouter()

// 订单列表数据
const orderList = ref([])
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const activeTab = ref('all')

// 促销活动数据
const activePromotions = ref([])
const hasDiscountPromotion = computed(() => {
  // 检查是否有满减类型的促销活动
  return activePromotions.value.some(promotion => promotion.type === 'discount')
})

// 订单详情数据
const orderNo = computed(() => route.query.orderNo as string)
const orderDetail = ref(null)
const loading = ref(false)
const orderReview = ref(null)

// 获取订单列表
const getOrderList = async () => {
  try {
    const params = {
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      status: activeTab.value === 'all' ? null : Number(activeTab.value)
    }

    const response = await getOrders(params)
    if (response.code === 200) {
      orderList.value = response.data.records
      total.value = response.data.total

      // 处理订单列表中的优惠信息
      orderList.value.forEach(order => {
        // 确保promotionAmount字段有值
        if (order.promotionAmount === null || order.promotionAmount === undefined) {
          order.promotionAmount = 0
        }

        // 确保payAmount字段有值
        if (order.payAmount === null || order.payAmount === undefined) {
          order.payAmount = order.totalAmount - order.promotionAmount
        }
      })

      // 检查已完成订单的评价状态
      await checkOrdersReviewStatus()
    }
  } catch (error) {
    console.error('获取订单列表失败:', error)
    ElMessage.error('获取订单列表失败')
  }
}

// 检查订单评价状态
const checkOrdersReviewStatus = async () => {
  // 只检查已完成的订单
  const completedOrders = orderList.value.filter(order => order.status === 3)
  if (completedOrders.length === 0) return

  // 批量获取订单详情和评价状态
  const orderPromises = completedOrders.map(async (order) => {
    try {
      // 获取订单详情
      const detailResponse = await getOrderDetail(order.orderNo)
      if (detailResponse.code === 200 && detailResponse.data.orderItems && detailResponse.data.orderItems.length > 0) {
        const firstItem = detailResponse.data.orderItems[0]

        // 检查订单是否已评价
        const reviewResponse = await checkReview(order.orderNo, firstItem.productId)
        if (reviewResponse.code === 200) {
          // 设置评价状态标记
          order.hasReview = reviewResponse.data
        } else {
          order.hasReview = false
        }
      } else {
        order.hasReview = false
      }
    } catch (error) {
      console.error(`检查订单 ${order.orderNo} 评价状态失败:`, error)
      // 如果检查失败，默认为未评价
      order.hasReview = false
    }
  })

  // 等待所有请求完成
  await Promise.all(orderPromises)
}

// 获取订单详情
const fetchOrderDetail = async (orderNo) => {
  if (!orderNo) {
    console.error('获取订单详情失败: 订单号为空')
    return
  }

  loading.value = true
  orderDetail.value = null

  try {
    console.log('正在获取订单详情，订单号:', orderNo)
    // 添加重试逻辑
    let retries = 3
    let response = null

    while (retries > 0) {
      try {
        response = await getOrderDetail(orderNo)
        console.log('订单详情API响应:', response)
        break // 如果成功获取数据，跳出循环
      } catch (err) {
        retries--
        if (retries === 0) throw err
        console.log(`获取订单详情失败，剩余重试次数: ${retries}`)
        await new Promise(resolve => setTimeout(resolve, 1000)) // 等待1秒后重试
      }
    }

    if (response && response.code === 200 && response.data) {
      orderDetail.value = response.data
      console.log('设置订单详情数据:', orderDetail.value)

      // 确保promotionAmount字段有值，如果为null或undefined则设为0
      if (orderDetail.value.order) {
        if (orderDetail.value.order.promotionAmount === null || orderDetail.value.order.promotionAmount === undefined) {
          orderDetail.value.order.promotionAmount = 0
        }

        // 确保payAmount字段有值
        if (orderDetail.value.order.payAmount === null || orderDetail.value.order.payAmount === undefined) {
          orderDetail.value.order.payAmount = orderDetail.value.order.totalAmount - orderDetail.value.order.promotionAmount
        }

        console.log('订单优惠信息:', {
          totalAmount: orderDetail.value.order.totalAmount,
          promotionAmount: orderDetail.value.order.promotionAmount,
          payAmount: orderDetail.value.order.payAmount
        })
      }

      // 如果订单状态为已完成，检查是否有评价
      if (orderDetail.value.order && orderDetail.value.order.status === 3 &&
          orderDetail.value.orderItems && orderDetail.value.orderItems.length > 0) {
        const firstItem = orderDetail.value.orderItems[0]
        fetchOrderReview(orderDetail.value.order.orderNo, firstItem.productId)
      } else {
        orderReview.value = null
      }
    } else {
      console.error('获取订单详情失败，响应码:', response ? response.code : '无响应', '响应数据:', response)
      ElMessage.error((response && response.message) || '获取订单详情失败')
      // 即使失败也不设置orderDetail为null，保持loading状态结束后显示重新加载按钮
    }
  } catch (error) {
    console.error('获取订单详情失败:', error)
    ElMessage.error('获取订单详情失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 监听路由参数变化，确保在路由参数变化时也能正确加载订单详情

// 监听orderNo变化
watch(orderNo, (newOrderNo, oldOrderNo) => {
  console.log('订单号变化:', oldOrderNo, '->', newOrderNo)
  if (newOrderNo) {
    fetchOrderDetail(newOrderNo)
  } else if (oldOrderNo) {
    // 从详情页返回列表页
    getOrderList()
  }
}, { immediate: true })

// 获取进行中的促销活动
const fetchActivePromotions = async () => {
  try {
    const response = await getActivePromotions()
    console.log('获取促销活动响应:', response)

    if (response.code === 200) {
      activePromotions.value = response.data
      console.log('获取到的促销活动:', activePromotions.value)
      console.log('是否有满减活动:', hasDiscountPromotion.value)
    }
  } catch (error) {
    console.error('获取促销活动失败:', error)
  }
}

// 页面加载时获取数据
onMounted(() => {
  // 获取促销活动
  fetchActivePromotions()

  if (orderNo.value) {
    console.log('页面挂载时加载订单详情:', orderNo.value)
    fetchOrderDetail(orderNo.value)
  } else {
    console.log('页面挂载时加载订单列表')
    getOrderList()
  }
})

// 查看订单详情
const viewOrderDetail = (orderNo) => {
  console.log('查看订单详情:', orderNo)
  // 先清空当前数据，避免显示旧数据
  orderDetail.value = null
  // 使用replace而不是push，避免浏览器历史堆积
  router.replace(`/user/orders?orderNo=${orderNo}`)
}

// 返回订单列表
const backToList = () => {
  router.push('/user/orders')
}

// 处理重新加载
const handleReload = () => {
  console.log('手动重新加载订单详情:', orderNo.value)
  if (orderNo.value) {
    // 清空当前数据，重新获取
    orderDetail.value = null
    fetchOrderDetail(orderNo.value)
  }
}

// 处理订单状态变化
const handleStatusChange = () => {
  currentPage.value = 1
  getOrderList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  currentPage.value = page
  getOrderList()
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  getOrderList()
}

// 获取订单状态标签
const getOrderStatusTag = (status) => {
  const statusMap = {
    0: { type: 'warning', label: '待付款' },
    1: { type: 'primary', label: '待发货' },
    2: { type: 'info', label: '待收货' },
    3: { type: 'success', label: '已完成' }
  }
  return statusMap[status] || { type: '', label: '未知状态' }
}

// 格式化日期
const formatDate = (dateStr) => {
  if (!dateStr) return ''
  const date = new Date(dateStr)
  return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`
}

// 支付订单
const payOrder = (orderNo) => {
  ElMessageBox.confirm('确定要支付此订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await payOrderApi(orderNo)
      if (response.code === 200) {
        ElMessage.success('支付成功')
        // 刷新订单详情或列表
        if (orderDetail.value) {
          fetchOrderDetail(orderNo)
        } else {
          getOrderList()
        }
      } else {
        ElMessage.error(response.message || '支付失败')
      }
    } catch (error) {
      console.error('支付订单失败:', error)
      ElMessage.error('支付失败，请确保余额充足')
    }
  }).catch(() => {
    // 取消支付
  })
}



// 确认收货
const confirmReceive = (orderNo, status) => {
  // 先检查订单状态是否为待收货(2)
  if (status !== 2) {
    ElMessage.error('只有待收货状态的订单才能确认收货')
    return
  }

  ElMessageBox.confirm('确认已收到商品吗？确认后订单将完成', '确认收货', {
    confirmButtonText: '确认收货',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await confirmReceiveOrder(orderNo)
      if (response.code === 200) {
        ElMessage.success('确认收货成功')
        // 刷新订单详情或列表
        if (orderDetail.value) {
          fetchOrderDetail(orderNo)
        } else {
          getOrderList()
        }
      } else {
        ElMessage.error(response.message || '确认收货失败')
      }
    } catch (error) {
      console.error('确认收货失败:', error)
      ElMessage.error('确认收货失败，请稍后重试')
    }
  }).catch(() => {
    // 用户取消操作
  })
}

// 评价对话框数据
const reviewDialogVisible = ref(false)
const reviewSubmitting = ref(false)
const reviewFormRef = ref(null)
const currentOrderItem = ref(null)

// 评价表单数据
const reviewForm = reactive({
  orderNo: '',
  productId: null,
  productName: '',
  rating: 5,
  content: '',
  anonymous: false
})

// 评价表单验证规则
const reviewRules = {
  rating: [
    { required: true, message: '请选择评分', trigger: 'change' }
  ],
  content: [
    { required: true, message: '请输入评价内容', trigger: 'blur' },
    { min: 5, max: 500, message: '评价内容长度在 5 到 500 个字符之间', trigger: 'blur' }
  ]
}

// 打开评价对话框
const reviewOrder = (order) => {
  // 如果是订单详情页
  if (orderDetail.value) {
    // 目前我们只支持对整个订单进行评价，所以取第一个商品
    const firstItem = orderDetail.value.orderItems[0]
    if (!firstItem) {
      ElMessage.warning('没有找到可评价的商品')
      return
    }

    currentOrderItem.value = firstItem
    reviewForm.orderNo = orderDetail.value.order.orderNo
    reviewForm.productId = firstItem.productId
    reviewForm.productName = firstItem.productName
  } else {
    // 如果是订单列表页，需要先获取订单详情
    ElMessage.info('请先进入订单详情页进行评价')
    return
  }

  // 检查是否已评价
  checkReview(reviewForm.orderNo, reviewForm.productId).then(response => {
    if (response.code === 200) {
      if (response.data) {
        ElMessage.warning('该商品已评价')
      } else {
        reviewDialogVisible.value = true
      }
    }
  }).catch(error => {
    console.error('检查评价状态失败:', error)
    ElMessage.error('检查评价状态失败')
  })
}

// 获取订单评价
const fetchOrderReview = async (orderNo, productId) => {
  try {
    const response = await getOrderReview(orderNo, productId)
    if (response.code === 200) {
      orderReview.value = response.data
      console.log('获取到订单评价:', orderReview.value)
    } else if (response.code === 404) {
      // 评价不存在，这是正常情况，不是错误
      console.log('订单尚未评价')
      orderReview.value = null
    } else {
      orderReview.value = null
    }
  } catch (error) {
    console.error('获取订单评价失败:', error)
    orderReview.value = null
  }
}

// 提交评价
const submitReview = () => {
  reviewFormRef.value.validate(async (valid) => {
    if (valid) {
      reviewSubmitting.value = true
      try {
        const params = {
          orderNo: reviewForm.orderNo,
          productId: reviewForm.productId,
          rating: reviewForm.rating,
          content: reviewForm.content,
          anonymous: reviewForm.anonymous ? 1 : 0
        }

        const response = await addReview(params)
        if (response.code === 200) {
          ElMessage.success('评价成功')
          reviewDialogVisible.value = false

          // 重置表单
          reviewForm.rating = 5
          reviewForm.content = ''
          reviewForm.anonymous = false

          // 获取新提交的评价
          fetchOrderReview(reviewForm.orderNo, reviewForm.productId)

          // 刷新订单详情
          if (orderDetail.value) {
            fetchOrderDetail(orderDetail.value.order.orderNo)
          }
        } else {
          ElMessage.error(response.message || '评价失败')
        }
      } catch (error) {
        console.error('提交评价失败:', error)
        ElMessage.error('提交评价失败，请稍后重试')
      } finally {
        reviewSubmitting.value = false
      }
    }
  })
}

// 取消订单
const cancelOrder = (orderNo) => {
  ElMessageBox.confirm('确定要取消此订单吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    try {
      const response = await cancelOrderApi(orderNo)
      if (response.code === 200) {
        ElMessage.success('订单已取消')
        // 如果在订单详情页取消订单，直接返回订单列表页
        if (orderDetail.value) {
          // 直接返回订单列表页，而不是尝试重新加载已删除的订单
          router.push('/user/orders')
        } else {
          // 如果在订单列表页取消订单，刷新列表
          getOrderList()
        }
      } else {
        ElMessage.error(response.message || '取消订单失败')
      }
    } catch (error) {
      console.error('取消订单失败:', error)
      ElMessage.error('取消订单失败')
    }
  }).catch(() => {
    // 取消操作
  })
}
</script>

<style scoped>
.orders-container {
  padding: 20px 0;
}

/* 订单状态导航条样式 */
.order-status-nav {
  display: flex;
  margin-bottom: 20px;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
  padding: 15px 20px;
  overflow-x: auto;
}

.status-item {
  padding: 8px 20px;
  margin-right: 15px;
  border-radius: 20px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
  background-color: #f5f7fa;
  color: #606266;
  text-align: center;
  user-select: none;
  white-space: nowrap;
}

.status-item:hover {
  background-color: #e6f1fc;
  color: #409EFF;
}

.status-item.active {
  background-color: #409EFF;
  color: white;
  font-weight: 500;
}

/* 订单列表样式 */
.order-card {
  margin-bottom: 20px;
  border-radius: 8px;
  overflow: hidden;
  transition: all 0.3s;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.order-card:hover {
  box-shadow: 0 4px 16px 0 rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.order-card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background-color: #f9f9f9;
  border-bottom: 1px solid #eee;
}

.order-info {
  display: flex;
  gap: 20px;
}

.order-no {
  font-weight: bold;
}

.order-card-body {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  cursor: pointer;
  background-color: #fff;
}

.order-summary-info p {
  margin: 8px 0;
  color: #606266;
  font-size: 14px;
}

.order-price-info {
  text-align: right;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.price-item {
  margin: 5px 0;
  color: #606266;
}

.pay-amount {
  font-size: 20px;
  color: #f56c6c;
  font-weight: bold;
  position: relative;
  display: inline-block;
}

.pay-amount::after {
  content: '';
  position: absolute;
  left: 0;
  right: 0;
  bottom: -2px;
  height: 4px;
  background-color: rgba(245, 108, 108, 0.1);
  border-radius: 2px;
}

.order-card-footer {
  padding: 15px 20px;
  background-color: #fff;
  border-top: 1px solid #f0f0f0;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.empty-orders {
  margin: 50px 0;
  background-color: #fff;
  border-radius: 8px;
  padding: 40px 0;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.05);
}

.pagination-container {
  margin-top: 30px;
  margin-bottom: 20px;
  display: flex;
  justify-content: center;
}

/* 订单详情样式 */
.order-detail {
  padding: 20px;
}

.back-button {
  margin-bottom: 20px;
}

.order-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.order-info {
  display: flex;
  justify-content: space-between;
  margin-bottom: 20px;
}

.order-section {
  flex: 1;
}

.order-section h3 {
  margin-bottom: 10px;
  color: #333;
}

.order-section p {
  margin: 5px 0;
  color: #666;
}

.order-items {
  margin-bottom: 20px;
}

.order-items h3 {
  margin-bottom: 10px;
  color: #333;
}

/* 商品图片样式已移除 */

.order-summary {
  margin-top: 20px;
  text-align: right;
}

.summary-item {
  display: flex;
  justify-content: flex-end;
  margin: 5px 0;
}

.summary-item span:first-child {
  margin-right: 10px;
}

.summary-item.total {
  font-size: 18px;
  font-weight: bold;
  color: #f56c6c;
}

.order-actions {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 加载中和空状态样式 */
.loading-card,
.empty-card {
  min-height: 300px;
}

.loading-container {
  padding: 20px;
}

.empty-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.detail-card {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.1) !important;
  border-radius: 8px;
}

/* 评价区域样式 */
.order-review-section {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 8px;
  border: 1px solid #eee;
}

.order-review-section h3 {
  margin-bottom: 15px;
  color: #333;
  font-size: 16px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.review-content {
  padding: 0 10px;
}

.review-rating {
  margin-bottom: 15px;
  display: flex;
  align-items: center;
}

.rating-label {
  margin-right: 10px;
  color: #666;
  font-weight: 500;
}

.review-text {
  margin-bottom: 15px;
}

.review-label {
  color: #666;
  font-weight: 500;
  display: block;
  margin-bottom: 5px;
}

.review-text p {
  margin: 5px 0;
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
  border: 1px solid #eee;
  color: #333;
}

.review-time {
  color: #999;
  font-size: 12px;
  text-align: right;
}

.review-time-label {
  margin-right: 5px;
}

/* 促销折扣样式 */
.summary-item.discount {
  color: #f56c6c;
  font-weight: bold;
}

.discount-amount {
  color: #f56c6c;
  font-weight: bold;
}

.discount-tag {
  margin-left: 5px;
  transform: scale(0.8);
}

.price-item.discount {
  color: #f56c6c;
}
</style>
